import os
from PIL import Image
from flask import current_app
from datetime import datetime

def save_image(file, folder):
    """保存图片并返回文件名"""
    if not file:
        return None
    
    filename = f"{datetime.now().strftime('%Y%m%d%H%M%S')}_{file.filename}"
    filepath = os.path.join(current_app.config['UPLOAD_FOLDER'], folder, filename)
    
    # 确保目录存在
    os.makedirs(os.path.dirname(filepath), exist_ok=True)
    
    # 保存并优化图片
    image = Image.open(file)
    image.thumbnail((800, 800))  # 调整图片大小
    image.save(filepath, quality=85, optimize=True)
    
    return filename

def allowed_file(filename, allowed_extensions=None):
    """检查文件类型是否允许"""
    if allowed_extensions is None:
        allowed_extensions = {'png', 'jpg', 'jpeg', 'gif'}
    return '.' in filename and \
           filename.rsplit('.', 1)[1].lower() in allowed_extensions 